using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Commerce.Common;
using Commerce.PayPal;

namespace CommerceForUmbraco.usercontrols
{
    public partial class Cart : System.Web.UI.UserControl
    {
        // currentOrder object
        protected Order currentOrder;
        protected decimal orderSubTotal = 0;

        public void UpdateCart()
        {
            OrderItemCollection orderItemCollection = OrderController.GetCartItems();

            try
            {
                rptBasket.DataSource = orderItemCollection;
                rptBasket.DataBind();
                
                decimal dTotal = 0;
                foreach (OrderItem item in orderItemCollection)
                {
                    dTotal += item.LineTotal;
                }

                orderSubTotal = dTotal;

            }
            catch (Exception ex)
            {
                emptyMessage.Text = "We're sorry but an error has occured.  " + ex.Message;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                UpdateCart();

        }

        public void R1_ItemCommand(Object sender, RepeaterCommandEventArgs e)
        {
            string action = ((ImageButton)e.CommandSource).CommandArgument;

            switch (action)
            {
                case "remove":
                    DeleteItem(sender, e);
                    break;
                case "update":
                    UpdateItem(sender, e);
                    break;
            }
        }

        protected void UpdateItem(Object sender, RepeaterCommandEventArgs e)
        {
            Label lblProductID = (Label)e.Item.FindControl("lblProductID");
            Label lblProductAttributes = (Label)e.Item.FindControl("lblProductAttributes");
            TextBox newQuantity = (TextBox)e.Item.FindControl("qtyEntry");
            int orderID = OrderController.GetCartOrderID();

            if (lblProductID != null && newQuantity !=null)
            {
                OrderController.AdjustQuantity(orderID, int.Parse(lblProductID.Text), lblProductAttributes.Text, int.Parse(newQuantity.Text));
            }

            UpdateCart();
        }

        protected void DeleteItem(Object sender, RepeaterCommandEventArgs e)
        {
            Label lblProductID = (Label)e.Item.FindControl("lblProductID");
            Label lblProductAttributes = (Label)e.Item.FindControl("lblProductAttributes");

            if (lblProductID != null)
            {
                OrderController.RemoveItem(int.Parse(lblProductID.Text), lblProductAttributes.Text);
            }

            UpdateCart();
        }

        protected void checkoutButton_Click(object sender, ImageClickEventArgs e)
        {
            // get checkout link from config
            Response.Redirect(Utility.GetCheckoutUrl(), true);

        }

        protected void ppExpressChecout_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                // set order information
                SetCurrentOrder();
                SetOrderInfo();

                // redirect to PayPal
                SetExpressCheckout();

            }
            catch (Exception ex)
            {
                emptyMessage.Visible = true;
                emptyMessage.Text = "We're sorry, an error occured.<br />" + ex.Message;
            }

        }

        protected void SetExpressCheckout()
        {
            try
            {
                // SetExpressCheckout
                APIWrapper wrapper = GetPPWrapper();

                string successURL = Utility.GetPayPalExpressCheckoutSuccessUrl();
                string failURL = Utility.GetPayPalExpressCheckoutFailUrl();
                string sUrl = "";

                if (currentOrder.Items.Count > 0)
                {
                    string ppToken = wrapper.SetExpressCheckout(string.Empty, currentOrder.CalculateSubTotal(),
                     successURL, failURL, false, new Address());
                    if (ppToken.ToLower().Contains("error"))
                    {
                        throw new Exception("PayPal has returned an error message: " + ppToken.ToString());
                    }
                    else
                    {

                        sUrl = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + ppToken;

                        if (!SiteConfig.APIIsLive)
                        {
                            sUrl = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + ppToken;
                        }

                        try
                        {
                            Response.Redirect(sUrl, false);
                        }
                        catch (Exception)
                        {
                            // ResultMessage1.ShowFail(x.Message);
                            throw;
                        }
                    }

                }
                else
                {
                    // send back to the cart page
                    Response.Redirect(Utility.GetCartUrl(), false);
                }

            }
            catch (Exception)
            {
                throw;
            }
        }

        protected void SetOrderInfo()
        {
            currentOrder.ShippingAddress = null;
            currentOrder.BillingAddress = null;
        }

        protected void SetCurrentOrder()
        {
            if (currentOrder == null)
                currentOrder = OrderController.GetCurrentOrder();
        }

        protected APIWrapper GetPPWrapper()
        {
            SiteConfig.Load();

            APIWrapper wrapper =
              new APIWrapper(SiteConfig.PayPalAPIAccountName
                    , SiteConfig.PayPalAPIAccountPassword
                    , SiteConfig.APIsignature
                    , (CurrencyCode)Enum.Parse(typeof(CurrencyCode), SiteConfig.defaultCurrencyCode)
                    , SiteConfig.APIIsLive);

            return wrapper;
        }
    }
}